﻿
// active-newDlg.cpp : 实现文件
//

#include "stdafx.h"
#include "active-new.h"
#include "active-newDlg.h"
#include "afxdialogex.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#define WM_SHOWMSG WM_USER+1
#define WM_ENABLE_WIN WM_USER+2
#define WM_SHOWPROCESS WM_USER+3
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
extern struct TPing
{
	int m_Loop;
	int m_Error;
	int m_AllTime;
};
extern int icmp_test(const char *addr, const char *parm, char *rOut, TPing &aPing);

IMPLEMENT_DYNAMIC(CactivenewDlg, CDialog)

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// 对话框数据
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CactivenewDlg 对话框




CactivenewDlg::CactivenewDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CactivenewDlg::IDD, pParent)
	, m_ShowMsg(_T(""))
	, m_Static_Msg(_T(""))
	, m_Local_Ip(_T(""))
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CactivenewDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Text(pDX, IDC_EDIT_MSG, m_ShowMsg);
	DDX_Text(pDX, IDC_STATIC_MSG, m_Static_Msg);
	DDX_Text(pDX, IDC_LOCAL_IP, m_Local_Ip);
	DDX_Control(pDX, IDC_PROGRESS_SHOW, m_Progress);
}

BEGIN_MESSAGE_MAP(CactivenewDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(FTP_BUTTON, &CactivenewDlg::OnFTPButton)
	ON_BN_CLICKED(ICMP_BUTTON, &CactivenewDlg::OnICMPButton)
	ON_MESSAGE(WM_SHOWMSG, &CactivenewDlg::OnShowMsg)
	ON_MESSAGE(WM_ENABLE_WIN, &CactivenewDlg::OnEnableWin)
	ON_MESSAGE(WM_SHOWPROCESS, &CactivenewDlg::OnShowProcess)
	ON_WM_CREATE()
	ON_BN_CLICKED(IDC_BTN_UP, &CactivenewDlg::OnBnClickedBtnUp)
	ON_BN_CLICKED(IDC_BTN_DOWN, &CactivenewDlg::OnBnClickedBtnDown)
END_MESSAGE_MAP()


// CactivenewDlg 消息处理程序

BOOL CactivenewDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 设置此对话框的图标。当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	ShowWindow(SW_MINIMIZE);

	// TODO: 在此添加额外的初始化代码

	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

void CactivenewDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CactivenewDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CactivenewDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}





void CactivenewDlg::OnFTPButton()
{
	// TODO: 速率测试
	SPARAM* sparam = new SPARAM;
	sparam->pThis = this;
	HANDLE handle = CreateThread(NULL, 0, OnSpeedTestProc, (PVOID *)sparam, 0, NULL);
	CloseHandle(handle);

	CWnd* wnd = GetDlgItem(FTP_BUTTON);
	wnd->EnableWindow(FALSE);
	CWnd* wnd1 = GetDlgItem(ICMP_BUTTON);
	wnd1->EnableWindow(FALSE);
}


void CactivenewDlg::OnICMPButton()
{
	// TODO: 质量测试
	SPARAM *sparam = new SPARAM;
	sparam->pThis = this;
	HANDLE handle = CreateThread(NULL, 0, OnQualityTestProc, (PVOID)sparam, 0, NULL);
	CloseHandle(handle);

	CWnd* wnd = GetDlgItem(FTP_BUTTON);
	wnd->EnableWindow(FALSE);
	CWnd* wnd1 = GetDlgItem(ICMP_BUTTON);
	wnd1->EnableWindow(FALSE);
}

DWORD WINAPI CactivenewDlg::OnSpeedTestProc(PVOID pvoid)
{
	CactivenewDlg *pNetTest = ((SPARAM*)pvoid)->pThis;
	HWND hwnd = pNetTest->m_hWnd;
	AccessNet aNet;
	TResult aRst;
	aRst.m_size = 0;
	aRst.m_time = 0;
	CString aUrl,aFile;
	aUrl = _T("/testwrn");
	aFile = _T("C:\\UpFile");
	time_t now;
	time(&now);
	srand(time(NULL));
	int ran = rand();
	aUrl.AppendFormat(_T("%d_%d"), ran, now);

	pNetTest->m_ShowMsg.Empty();
	pNetTest->m_ShowMsg.Append(_T("正在测试上传速率。。。"));
	::PostMessage(hwnd, WM_SHOWMSG, NULL, NULL);

	BOOL rt = aNet.UpLoadFtpFile(pNetTest->m_Ser, aUrl, aFile, aRst, pNetTest);
	CString atmpstr;
	if (rt)
	{
		pNetTest->m_ShowMsg.Empty();
		pNetTest->m_ShowMsg.AppendFormat(_T("上传测试：\r\n大小：%4.3fM\t时间：%4.3fs\t速率：%dkbps"), 
			aRst.m_size*1.0/1024/1024, aRst.m_time*1.0/1000, (aRst.m_size/aRst.m_time)*1000*8/1024);
	}
	else
	{
		pNetTest->m_ShowMsg.Empty();
		pNetTest->m_ShowMsg.Append(_T("上传测试失败。\r\n"));
	}
	atmpstr = pNetTest->m_ShowMsg;
	pNetTest->m_ShowMsg.Append(_T("\r\n正在测试下载速率。。。"));
	::PostMessage(hwnd, WM_SHOWMSG, NULL, NULL);

	TResult aRst1;
	aRst1.m_size = 0;
	aRst1.m_time = 0;
	CString aUrlFile = _T("/downLoad");
	CString aLocFile = _T("c:\\a11.exe");
	BOOL rt1 = aNet.DownLoadFtpFile(pNetTest->m_Ser, aUrlFile, aLocFile, aRst1, pNetTest);

	pNetTest->m_ShowMsg = atmpstr;
	if (rt1)
	{
		pNetTest->m_ShowMsg.AppendFormat(_T("\r\n下载测试：\r\n大小：%4.3fM\t时间：%4.3fs\t速率：%dkbps"), 
			aRst1.m_size*1.0/1024/1024, aRst1.m_time*1.0/1000, (aRst1.m_size/aRst1.m_time)*1000*8/1024);
		::PostMessage(hwnd, WM_SHOWMSG, NULL, NULL);
	}
	else
	{
		pNetTest->m_ShowMsg.Append(_T("\r\n下载测试失败。\r\n"));
		::PostMessage(hwnd, WM_SHOWMSG, NULL, NULL);
	}

	if (aRst1.m_size != 0 || aRst.m_size != 0)
	{
		CString agetRst;
		BOOL rt2 = aNet.UpDateRst(agetRst, aRst1, aRst);
		if (rt2)
		{
			pNetTest->m_ShowMsg.Append("\r\n测试结果");
			if (agetRst.Mid(0, 2).Compare("OK") == 0)
			{
				pNetTest->m_ShowMsg.Append(_T("上传成功。"));
			} 
			else
			{
				pNetTest->m_ShowMsg.Append(_T("上传失败。"));
			}
			//pNetTest->m_ShowMsg.Append(agetRst);
			::PostMessage(hwnd, WM_SHOWMSG, NULL, NULL);
		}
		else
		{
			pNetTest->m_ShowMsg.Append(_T("\r\n上传结果失败。"));
			::PostMessage(hwnd, WM_SHOWMSG, NULL, NULL);
		}
	}
	
	::PostMessage(hwnd, WM_ENABLE_WIN, NULL, NULL);
	return 0;
}

DWORD WINAPI CactivenewDlg::OnQualityTestProc(PVOID pvoid)
{
	CactivenewDlg *pNetTest = ((SPARAM*)pvoid)->pThis;
	HWND hwnd = pNetTest->m_hWnd;

	char* aAddr = _T("www.google.com");
	char *sOut = (char*)malloc(1024);
	AccessNet aNet;
	if(sOut != NULL){
		pNetTest->m_ShowMsg.Empty();
		pNetTest->m_ShowMsg.Append(_T("正在进行质量测试。。。"));
		::PostMessage(hwnd, WM_SHOWMSG, NULL, NULL);


		if (pNetTest->m_Ser.m_Server.IsEmpty())
		{
			if (aNet.CheckFtpServer(pNetTest->m_Ser,pNetTest->m_Local_Ip,pNetTest->m_Agent))
			{
				aAddr = (char*)(LPCTSTR)(pNetTest->m_Ser.m_Server);
			}
		}
		else
		{
			aAddr = (char*)(LPCTSTR)(pNetTest->m_Ser.m_Server);
		}
		TPing aPing;
		aPing.m_AllTime = 0;
		aPing.m_Error = 0;
		aPing.m_Loop = 0;
		CString sDate;
		memset(sOut, 0, 1024);
		icmp_test(aAddr, "-t", sOut, aPing);

		sDate.AppendFormat(_T("%s--------"), sOut);
		memset(sOut, 0, 1024);
		icmp_test(aAddr, "-c", sOut, aPing);
		pNetTest->m_ShowMsg.Empty();
		if (aPing.m_Loop > 0)
		{
			pNetTest->m_ShowMsg.AppendFormat(_T("网络丢包率是%3.3f%%"),((100.0*aPing.m_Error)/aPing.m_Loop));
			if (aPing.m_Loop - aPing.m_Error != 0)
			{
				if (aPing.m_AllTime < aPing.m_Loop - aPing.m_Error)
				{
					pNetTest->m_ShowMsg.Append(_T("，网络延迟小于1毫秒！\r\n"));
				} 
				else
				{
					pNetTest->m_ShowMsg.AppendFormat(_T("，网络延迟是%4.3f毫秒！\r\n"),(float)(1.0*aPing.m_AllTime)/(aPing.m_Loop - aPing.m_Error));
				}
			}
			else
				pNetTest->m_ShowMsg.Append(_T("。\r\n"));
		}
		else
		{
			pNetTest->m_ShowMsg.Append(_T("质量测试失败，请检查网络后再进行测试。\r\n"));
		}

		::PostMessage(hwnd, WM_SHOWMSG, NULL, NULL);

		sDate.AppendFormat(_T("%s"), sOut);
		// http://61.183.149.138/netest/SetTestData.jspx?action=icmp	
		CString aActionData, aRst;
		aActionData.Format(_T("target=%s&icmptxt=%s"), aAddr, sDate);
		BOOL rt = aNet.DoHttpPost(aActionData, aRst);

		if (rt)
		{
			if (aRst.Mid(0, 2).Compare(_T("OK")) == 0)
			{
				pNetTest->m_ShowMsg.Append(_T("上传质量测试结果成功。"));
			} 
			else
			{
				pNetTest->m_ShowMsg.Append(_T("上传质量测试结果失败。"));
			}
			//pNetTest->m_ShowMsg = aRst;
			::PostMessage(hwnd, WM_SHOWMSG, NULL, NULL);
		}
		else
		{
			pNetTest->m_ShowMsg.Append(_T("上传质量测试结果失败。"));
			::PostMessage(hwnd, WM_SHOWMSG, NULL, NULL);
		}
		free(sOut);
		sOut = NULL;
	}
	::PostMessage(hwnd, WM_ENABLE_WIN, NULL, NULL);
	return 0;
}

LRESULT CactivenewDlg::OnShowProcess(WPARAM wparam, LPARAM lparam)
{
	CWnd* wnd = GetDlgItem(IDC_EDIT_MSG);
	wnd->ShowWindow(SW_HIDE);
	CWnd* wnd1 = GetDlgItem(IDC_PROGRESS_SHOW);
	wnd1->ShowWindow(SW_SHOW);
	CWnd* wnd2 = GetDlgItem(IDC_STATIC_MSG);
	wnd2->ShowWindow(SW_SHOW);
	m_Static_Msg.Empty();
	if ((int)wparam == 1)
	{
		m_Static_Msg.Append(_T("当前状态：已经上传"));
	} 
	else
	{
		m_Static_Msg.Append(_T("当前状态：已经下载"));
	}

	m_Static_Msg.AppendFormat(_T("%4.3fM/%4.3fM（%4.3f%%）。"), 1.0*atmpResult.m_size/1024/1024,
		1.0*atmpResult.m_total/1024/1024, 100.0*atmpResult.m_size/atmpResult.m_total);
	m_Progress.SetPos(100*atmpResult.m_size/atmpResult.m_total);
	UpdateData(FALSE);
	UpdateWindow();
	return 0;
}

LRESULT CactivenewDlg::OnShowMsg(WPARAM wparam, LPARAM lparam)
{
	CWnd* wnd = GetDlgItem(IDC_EDIT_MSG);
	wnd->ShowWindow(SW_SHOW);
	CWnd* wnd1 = GetDlgItem(IDC_PROGRESS_SHOW);
	wnd1->ShowWindow(SW_HIDE);
	CWnd* wnd2 = GetDlgItem(IDC_STATIC_MSG);
	wnd2->ShowWindow(SW_HIDE);
	UpdateData(FALSE);
	UpdateWindow();
	return 0;
}

LRESULT CactivenewDlg::OnEnableWin(WPARAM wparam, LPARAM lparam)
{
	m_Ser.m_Server.Empty();
	m_Ser.m_Name.Empty();
	m_Ser.m_Pass.Empty();
	CWnd* wnd = GetDlgItem(FTP_BUTTON);
	wnd->EnableWindow(TRUE);
	CWnd* wnd1 = GetDlgItem(ICMP_BUTTON);
	wnd1->EnableWindow(TRUE);
	return 0;
}

int CactivenewDlg::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CDialog::OnCreate(lpCreateStruct) == -1)
		return -1;

	// TODO:  
		SPARAM *sparam = new SPARAM;
		sparam->pThis = this;
		HANDLE handle = CreateThread(NULL, 0, OnLocalIpProc, (PVOID)sparam, 0, NULL);
		CloseHandle(handle);
	return 0;
}

DWORD WINAPI CactivenewDlg::OnLocalIpProc(PVOID pvoid)
{
	CactivenewDlg *pNetTest = ((SPARAM*)pvoid)->pThis;
	pNetTest->m_Local_Ip.Empty();
	HWND hwnd = pNetTest->m_hWnd;
	char szHostName[128];
	char szT[20];
	if( gethostname(szHostName, 128) == 0 )
	{
		// Get host adresses
		struct hostent * pHost;	
		pHost = gethostbyname(szHostName); 
		int i; 	
		for( i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ ) 	
		{
			char str[100]; 		
			char addr[20];
			int j;  		
			LPCSTR psz=inet_ntoa (*(struct in_addr *)pHost->h_addr_list[i]);
			//printf(psz);
			pNetTest->m_Local_Ip.Append(psz);
			//pNetTest->m_Local_Ip.Append(_T(";"));
			break;
		}
		//
		/*
		if(pNetTest->m_Local_Ip.GetLength()>0){
			AccessNet aNet;
			CString aRst;
			BOOL rt = aNet.DoLocalIp(pNetTest->m_Local_Ip,aRst);
			if (rt)
			{
				//m_ShowMsg = aRst;
				pNetTest->UpdateData(FALSE);
				pNetTest->UpdateWindow();
			}
		}
		*/
		//build User-Agent
		HKEY hKey;
		LONG ReturnValue;
		DWORD type;
		DWORD dwSize;
		LONG lReturn;
		char  strBuf[100];
		//IE
		ReturnValue = RegOpenKeyEx (HKEY_CURRENT_USER,
			"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",
			0,KEY_ALL_ACCESS, &hKey);
		if(ReturnValue == ERROR_SUCCESS){
			dwSize = 100;
			lReturn = RegQueryValueEx (hKey, "User Agent", NULL,
				&type, (BYTE *)strBuf, &dwSize);
			RegCloseKey (hKey);
			hKey=NULL;
			pNetTest->m_Agent.Empty();
			pNetTest->m_Agent.Format("%s",strBuf);
			pNetTest->m_Agent.TrimLeft();
			pNetTest->m_Agent.TrimRight();
			int p1 = pNetTest->m_Agent.Find(";");
			if(p1>0){
				int p2 = pNetTest->m_Agent.Find(";",p1+1);
				if(p2>0){
					pNetTest->m_Agent = pNetTest->m_Agent.Mid(0,p2);
				}
			}
		} else {
			pNetTest->m_Agent.Empty();
			pNetTest->m_Agent.Format("%s",_T("Mozilla/4.0 (compatible; MSIE >6"));
		}
		
		//OS
			ReturnValue = RegOpenKeyEx (HKEY_LOCAL_MACHINE, 
		                       "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", 
							   0,KEY_ALL_ACCESS, &hKey);

			if(ReturnValue == ERROR_SUCCESS){
				//OS Name
				memset(strBuf,0, sizeof(strBuf));
				dwSize = 100;
				LONG lReturn = RegQueryValueEx (hKey, "ProductName", NULL,
					&type, (BYTE *)strBuf, &dwSize);
				if(lReturn == ERROR_SUCCESS)
				{
					pNetTest->m_Agent.AppendFormat("; %s",strBuf);
				}
				//SP
				memset(strBuf,0, sizeof(strBuf));
				dwSize = 100;
				lReturn = RegQueryValueEx (hKey, "CSDVersion", NULL,
					&type, (BYTE *)strBuf, &dwSize);
				if(lReturn == ERROR_SUCCESS)
				{
					pNetTest->m_Agent.AppendFormat("; %s",strBuf);
				}
				//CurrentVersion
				memset(strBuf,0, sizeof(strBuf));
				dwSize = 100;
				lReturn = RegQueryValueEx (hKey, "CurrentVersion", NULL,
					&type, (BYTE *)strBuf, &dwSize);
				if(lReturn == ERROR_SUCCESS)
				{
					pNetTest->m_Agent.AppendFormat("; %s",strBuf);
				}
				//ProductId
				memset(strBuf,0, sizeof(strBuf));
				dwSize = 100;
				lReturn = RegQueryValueEx (hKey, "ProductId", NULL,
					&type, (BYTE *)strBuf, &dwSize);
				if(lReturn == ERROR_SUCCESS)
				{
					pNetTest->m_Agent.AppendFormat("; %s",strBuf);
				}
				
				//RegisteredOwner
				memset(strBuf,0, sizeof(strBuf));
				dwSize = 100;
				lReturn = RegQueryValueEx (hKey, "RegisteredOwner", NULL,
					&type, (BYTE *)strBuf, &dwSize);
				if(lReturn == ERROR_SUCCESS)
				{
					pNetTest->m_Agent.AppendFormat("; %s)",strBuf);
				}
				memset(strBuf,0, sizeof(strBuf));
				RegCloseKey (hKey);
				hKey=NULL;
			}//end OS
		//end build User-Agent

	}
	return 0;
}

void CactivenewDlg::OnBnClickedBtnUp()
{
	// TODO: Up
	
	AccessNet aNet;
	TResult aRst;
	CString aUrl,aFile, aServer;
	aServer = _T("172.16.2.39");
	aUrl = _T("/testw.txt");
	aFile = _T("E:\\Tools\\test.txt");
	BOOL rt = aNet.UpLoadFtpFile(m_Ser, aUrl, aFile, aRst,this);

	if (rt)
	{
		m_ShowMsg.Empty();
		m_ShowMsg.AppendFormat("size:%d\r\ntime:%d", aRst.m_size, aRst.m_time);
		UpdateData(FALSE);
	}
}


void CactivenewDlg::OnBnClickedBtnDown()
{
	// TODO: Down
	AccessNet aNet;

	TResult aRst;
	CString aServer = _T("172.16.2.39");
	CString aUrlFile = _T("/downLoad");
	CString aLocFile = _T("c:\\a11.exe");
	BOOL rt = aNet.DownLoadFtpFile(m_Ser, aUrlFile, aLocFile, aRst,this);

	if (rt)
	{
		m_ShowMsg.Empty();
		m_ShowMsg.AppendFormat("size:%d\r\ntime:%d", aRst.m_size, aRst.m_time);
		UpdateData(FALSE);
	}
}



